# verison:python3.8
import codecs
import json
from scipy.spatial.distance import cdist
import time
from numpy import array as nparr
from numpy import arange as nprange

from string_process import SP


# ====================================  test  ===================================================

# 另存为json文件
def write_to_format_json(data, name):
    json_file = codecs.open(name, 'w+', encoding='UTF-8')
    json_file.write("""{\n\t"data":[\n""")
    for i, node in enumerate(data):
        # if(i > 100):
        # 	break
        item_json = json.dumps(node, ensure_ascii=False)
        json_file.write('\t\t' + item_json + ',\n')

    json_file.write('\t]\n}')
    json_file.close()


def ReadJsonFromTaipei():
    # FileName = "Taipei_all_private.json"
    FileName = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/taipei.json"

    with open(FileName, encoding='utf-8-sig', errors='ignore') as f:
        Datas = json.load(f, strict=False)

        f.close()
    return Datas


def my_cdist(xa, xb):
    distance = cdist([xa], [xb], metric='euclidean')
    return distance.tolist()[0]


def dist_betwen(from_json, to_betwen):
    streets = read_point_from_json(from_json)['data']

    streets = [[float(i[0]), float(i[1])] for i in streets]
    points_with_dist = [[p, my_cdist(streets[i - 1], streets[i]), p[1], p[0]] for i, p in enumerate(streets[1:])]

    write_to_format_json(points_with_dist, to_betwen)

    return 0


def get_dist_betwen():
    # f_json = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/taipei02.json"
    # t_json = f"betwen_map.json"
    f_json = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/Taipei_all_private.json"
    t_json = f"betwen_Taipei_all_private.json"
    dist_betwen(f_json, t_json)


def test_cdist():  # 计算两个坐标点距离
    distance = cdist([[25.0393859, 121.5576824]], [[25.039797, 121.5576898]], metric='euclidean')
    dist_list = list(distance.tolist()[0])
    print(dist_list)


# ====================================  test  ===================================================

def re2(em):
    return em[0]


def write_to_json(data, name):
    tmp_data = {}
    tmp_data["data"] = data
    tmp_json = json.dumps(tmp_data, ensure_ascii=False)
    with open(name, 'w+') as f:
        f.write(tmp_json)


# 从json文件读取坐标合集
def read_point_from_json(FileName):
    Datas = SP.trans_json_text_to_json(FileName)
    return Datas


def filter_point(from_json, to_json, dist, count):
    streets = read_point_from_json(from_json)['data']

    start = 0
    new_data = list()
    new_append = new_data.append

    tmp_loop = []

    streets = [[float(i[1]), float(i[0])] for i in streets]
    while (1):
        # 获取坐标点之间的距离
        distance = cdist([streets[start]], nparr(streets), metric='euclidean')
        dist_list = list(distance.tolist()[0])
        len_dist_list = len(dist_list)

        # index_dist_list = [[d,i,s] for d,i,s in zip(dist_list,nprange(len_dist_list),streets)]
        index_dist_list = [[dist_list[i], i, streets[i]] for i in range(len_dist_list)]

        tmp_loop = []

        # 按距离筛选坐标点
        # "x[0] > dist" 此处的判断也可以选择更加严密的范围
        tmp_loop = list(filter(lambda x: x[0] > dist, index_dist_list))

        # print(f"---------------------------len(tmp_loop)---{len(tmp_loop)},")#{tmp_loop[:20]}
        if (len(tmp_loop) < 1):
            break

        # 新的起始点
        start = tmp_loop.index(min(tmp_loop, key=re2))
        new_append(tmp_loop[start])

        streets = [i[2] for i in tmp_loop]
        print(f"(tmp_loop[start]: {tmp_loop[start]})  {'-' * 5}  len(streets):{len(streets)}\n")

        if (count > 0 and len(new_data) > count):
            break

    print(f"(len(new_data):{len(new_data)})\n")

    # 另存筛选出待爬起的坐标点到json文件
    write_to_json(new_data, to_json)
    print('ok')


# 按照固定间距筛选，从json文件中筛选坐标，方便下一步爬取街景图片
def get_point():
    # 0.0004代表40米，其他距离以此计算
    # v_dist = float(0.00040)
    # v_dist = float(0.00100)
    v_dist = float(0.00150)
    count = 0
    # f_json = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/taipei02.json"
    f_json = "/home/wtgg/Downloads/liuzheng/Street_scene/bak/taipei02.json"
    t_json = f"Taipei_{str(count)}_{str(int(v_dist * 100000))}m.json"
    # f_json = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/Taipei_all_private.json"
    # t_json = f"Taipei_all_private_{str(count)}_{str(int(v_dist*100000))}m.json"
    print(t_json)
    filter_point(f_json, t_json, v_dist, count)


if __name__ == "__main__":
    print("start_time: ", time.asctime(time.localtime(time.time())))
    get_point()

    # get_dist_betwen()

    # test_cdist()
    end_time = time.time()
    print("end_time: ", time.asctime(time.localtime(time.time())))
